<?php 

/**
* 自己设计的上传类
*/
class Upload 
{
	public $path;//上传目录
	public $size;//限制上传字节
	public $type;//限制上传类型
	public $name;//生成上传文件名
	public $uploadData; //上传的文件信息
	public $key; //上传的键名
	public $array; //构建新的$_FILES数组,实现每个图片能独立上传
	      
/**
* 0 => string '271630.jpg' (length=10)   			图片名
* 1 => string 'image/jpeg' (length=10)  			图片格式
* 2 => string 'H:\wamp\tmp\phpABF9.tmp' (length=23) 图片路径
* 3 => int 0										报错信息
* 4 => int 315673									字节大小
*/
	// 构造函数 
	function __construct($config=array())
	{
		$this->path = isset($config['path']) ? $config['path'] : C('UPLOAD_PATH');
		$this->size = isset($config['size']) ? $config['size'] : C('UPLOAD_SIZE');
		$this->type = isset($config['type']) ? $config['type'] : C('UPLOAD_TYPE');
		$this->name = isset($config['name']) ? $config['name'] : C('UPLOAD_NAME');
	}
	/**
	 * 上传保存图片
	 */
	public function save(){
		$this->uploadData=$_FILES;
		//var_dump($_FILES);
		$this->key=key($_FILES);
		$this->_arr();
		$this->_check();
		$this->_move();
	}

	/**
	 * 检测图片是否条例要求
	 */
	private function _arr(){
		//将上传文件重组成2维索引数组
		$arr = array();
		if(!is_array($this->uploadData[$this->key]['name'])){
			foreach ($this->uploadData[$this->key] as $value) {
				array_push($arr, $value);
			}
			$this->array[0] = $arr;
		}else{
			for ($i=0; $i < count($this->uploadData[$this->key]['name']); $i++) { 
				foreach ($this->uploadData[$this->key] as $value) {
					array_push($arr, $value[$i]);
				}	
				$this->array[$i] = $arr;
				$arr = array();
			}		
		}
	}
	private  function _check(){
		foreach ($this->array as $key => $value) {			
			$a = $this->_type($value[0], $key+1);
			$b = $this->_size($value[4], $key+1);
			if($a == 1||$b == 1){
				unset($this->array[$key]);
			}
		}
		if ($this->array == array()) {
			include 'error.html';						
			exit;
		}			
	}

	//判断大小
	private function _size($size, $num){
		if($size>$this->size){

			$str =  "您的第".$num."个文件大小超过限制，请重新处理";

			echo "<script>alert('".$str."');</script>";
						
			return 1;
		}else{
			return 2;
		}
	}

	//检测类型
	private function _type($type, $num){

		$a = $type;

		$type = strrchr($type, '.');

		if(!in_array($type, $this->type)){

			$str = implode(',', $this->type);
			
			$str = "您的第".$num."个文件"."“.$a.”"."的类型不对，请上传".$str."类型的文件";	

			//echo '<script>alert("验证码不正确，请重新输入！"); </script>';

			echo "<script>alert('".$str."');</script>";

			return 1;
		}else{
			return 2;
		}
		
	}
	/**
	 * 移动图片到指定位置
	 */
	private  function _move(){
		foreach ($this->array as $key => $value) {			
			$this->_movefile($value[2], $value[0]);
		}
	}

	//移动文件
	private  function _movefile($tmpPath, $name){
		if(is_uploaded_file($tmpPath)){
			$dir = $this->path;

			!is_dir($dir)? mkdir($dir,777,true) : '' ;

			$name = iconv("UTF-8","gb2312", $name);

			$this->name = iconv("UTF-8","gb2312", $this->name);

			$path = $dir.$this->name.$name;

			move_uploaded_file($tmpPath,$path);
		}
	}

}

 ?>